package com.tanhua.server.service;


import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.api.CommentsApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Service
public class CommentsService {

    @DubboReference
    private CommentsApi commentsApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    /*圈子---发布评论*/
    public void saveComments(String movementId, String comment) {
        //获取当前用户id
        Long userId = UserHolder.getUserId();
        //构造Comment
        Comment comment1 = new Comment();
        comment1.setPublishId(new ObjectId(movementId));
        comment1.setCommentType(CommentType.COMMENT.getType());
        comment1.setContent(comment);
        comment1.setUserId(userId);
        comment1.setCreated(System.currentTimeMillis());
        //调用api将数据添加到数据库
        commentsApi.save(comment1);
    }

    /*圈子---评论列表*/
    public PageResult findComments(Integer page, Integer pagesize, String movementId) {
        //查询改动态的评论信息
        List<Comment> list = commentsApi.findComments(movementId,CommentType.COMMENT, page, pagesize);
        //判断list是否为空
        if (CollUtil.isEmpty(list)) {
            return new PageResult();
        }
        //获取评论人的信息
        List<Long> userId = CollUtil.getFieldValues(list, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userId, null);
        //循环list，构造vo对象
        List<CommentVo> vos = new ArrayList<>();
        for (Comment comment : list) {
            UserInfo userInfo = map.get(comment.getUserId());
            if (userInfo != null) {
                CommentVo commentVo = CommentVo.init(userInfo, comment);
                vos.add(commentVo);
            }
        }return new PageResult(page,pagesize,0L,vos);
    }
}
